var service = new EbeimService();

function setNId(nid,value){
	if(nid.indexOf('DS-')==0){
		if(!service.nids) service.nids = {};
		service.nids[nid] = value;
	}
}

var htmlOfProcess = {}
function setWhole(dsId,version,path){
	var processBarOfBottom = $("#processBarOfBottom");
	var key  = $("#processBarOfBottom .whole")[0].getAttribute('nid');
	if(key==''){
		htmlOfProcess['def'] = processBarOfBottom.html();	
	}else{
		htmlOfProcess[key] = processBarOfBottom.html();
	}
	
	processBarOfBottom.empty();
	if(htmlOfProcess[dsId]){
		processBarOfBottom.html(htmlOfProcess[dsId]);
	}else{
		processBarOfBottom.html(htmlOfProcess['def']);
		$(".whole").attr("nid",dsId);
		$(".whole").attr("id","bartd"+dsId);
		$(".whole").attr("version",version);
		$(".whole").attr("path",path);
	}
}
$(function(){
	var jlist = $("#j-list"); 
	var jreset = $("#j-reset"); 
	var jbackupList = $("#j-backupList");
	var jupLevel = $("#j-upLevel");
	var jbackupMore = $("#j-backupMore");
	var jbackupInp = $("#j-backupInp");
	var jback = $("#j-back");
	var jaddress = $("#j-address");
	var jwhole = $("#j-whole");
	
	var setting;
	var zPath;
	var zNodes =[];
	var upLevel = "";
	var key = true;
	var terminalId = plugin.GetQueryString("terminalId");
	var dsId = plugin.GetQueryString("dsId");
	
	var tpl = (function(){
        var tpl = {};
        $("script[type='text/ysmart']").each(function(){
            var t = $(this);
            tpl[t.attr("data-name")] = t.html();
        });
        return tpl;
    })();
	
	var searchVar = {
		dsId: dsId,
		version:plugin.GetQueryString("version"),
		path:plugin.GetQueryString("path")
    }
	
	setWhole(searchVar.dsId, searchVar.version, searchVar.path);
	
	var backupVar = {
		backupLog:{dsId : dsId,status:0},
		pages:{
			startPos : 1,
			pageSize : 5
		}
    }
	
	setting = {
		async: {
            enable: true,
            url: "/rest/datasource/menu",
            autoParam: ["id","type","version","path","dsId","root"],
            dataType: "json",
            dataFilter:function(treeId, parentNode, responseData){
            	if(responseData.code == "200"){
            		var nodes = [];
                	getTree(responseData.list,nodes);
                	return nodes;
            	}else{
            		plugin.msgtip({type: "e",msg: responseData.message});
            	}
            	
            },
            type:"get"
        },
        view: {
            fontCss: getFont,
            dblClickExpand: false,
            showLine: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: onClick,
            onExpand:function(event, treeId, treeNode){
            	if(key){
            		key = false;
	            	var treeObj = $.fn.zTree.getZTreeObj(treeId);
	            	var dsNodes = treeObj.getNodesByParam("id", dsId);
	            	if (dsNodes.length>0) {
	            		treeObj.selectNode(dsNodes[0]);	
	            		var p = dsNodes[0].getParentNode();
		            	zPath = dsNodes[0].name;
		            	while (p != null){
		            		zPath = p.name + " / " + zPath;
		        	    	p = p.getParentNode();
		            	}
		            	jaddress.html(zPath);
	        		}
            	}
            }
        }
    };
	
	jbackupMore.bind("click",function(){
		$(this).css("display","none");
		backupVar.pages.pageSize = 0;
		getBackuplogs();
	})
	
	jreset.bind("click",function(){
		var version = $(".j-backupItem").eq(0).attr("data-version");
		searchVar.version = version;
		backupVar.pages.pageSize = 5
		jbackupMore.css("display","block");
		getList();
		getBackuplogs();
	})
	
	jwhole.bind("click",function(){
		var dsId = $(".whole").attr("nid");
		var version = $(".whole").attr("version");
		var path = $(".whole").attr("path");
		directors(dsId,path.split("\\").join("\\\\"),version,'',dsId,dsId)
	})
	
	jupLevel.bind("click",function(){
		if(upLevel==""){
			setWhole(searchVar.dsId, searchVar.version, "/");
			plugin.msgtip({type: "i",msg: "已为当前数据源的最高层级"});
			return false;
		}
		var parent = "/";
		var idx = upLevel.lastIndexOf("\\");
		if(idx!=-1){
			parent = upLevel.substring(0,idx);
		}
		
		setWhole(searchVar.dsId, searchVar.version, parent==""?"/":parent);
		
		upLevel = parent;
		searchVar.path = parent;
		var idz = zPath.lastIndexOf("\/");
		zPath = zPath.substring(0,idz);
		jaddress.html(zPath);
		getList();
	})
	
	jback.bind("click",function(){
		history.back(-1);
	})
	
	jbackupList.delegate(".j-backupItem","click",function(){
		var t = $(this), version = t.attr("data-version");
		searchVar.version = version;
		jbackupInp.val(t.html());
		getList();
	})
	
	jlist.delegate(".j-listItem","click",function(){
		var t = $(this), path = t.attr("data-path");
		
		setWhole(searchVar.dsId, searchVar.version, path);
		
		searchVar.path = path;
		upLevel = path;
		var idz = path.lastIndexOf("\\");
		path = path.substring(idz,path.length).split("\\").join("\/");
		zPath = zPath + path;
		jaddress.html(zPath);
		getList();
	})
	
	service.getMenuTree({type:"0"},function(json){
		if(json.code == "200"){
			getTree(json.list,zNodes);
			$.fn.zTree.init($("#treeDemo"), setting, zNodes);
			var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
			var terminalNodes = treeObj.getNodesByParam("id", terminalId);
			if (terminalNodes.length>0) {
				treeObj.expandNode(terminalNodes[0], true ,false,true,true);		
			}
		}else{
			plugin.msgtip({type: "e",msg: json.message});
		}
	});
	
	var getList = function(){
		service.getFileList(searchVar,function(json){
			if(json.code == 500){
				plugin.msgtip({type: "i",msg: json.message});
				jlist.html("");
				return false
			}
			for(var i in json){
				json[i].fileSize = fileSizeTransfer(json[i].fileSize);
				json[i].dsId = searchVar.dsId;
				json[i].version = searchVar.version;
				/*json[i].path = json[i].path.split("\\").join("\\\\");*/
			}
			jlist.html(plugin.ysmart(tpl.list, json));	
			getDownloadProcessBar();
		});
	}
	var getBackuplogs = function(callback){
		service.getBackuplogs(backupVar,function(json){
			var list = "";
			for(var i = 0; i < json.list.objList.length; i++){
				var btime = json.list.objList[i].beginTime;
				if (btime == 0) {
					btime = "---"
				} else {
					btime = getTimeStr(btime);
				}
				if(json.list.objList[i].versionMajor == searchVar.version){
					jbackupInp.val(btime);
				}
				list = list+"<li class='j-backupItem' data-version='"+json.list.objList[i].versionMajor+".0'>"+btime
			}
			jbackupList.html(list);
		})
	}
	getList();
	getBackuplogs();
	
	function onClick(e,treeId, treeNode) {
		if(!treeNode.dsId){
			$("#"+treeNode.tId+"_a").removeClass("curSelectedNode");
			return false;
		}
		searchVar.dsId = treeNode.dsId;
		searchVar.version = treeNode.version;
		searchVar.path = treeNode.path;
		setWhole(searchVar.dsId, searchVar.version, searchVar.path);
		
		if(treeNode.path == "/"){
			upLevel = "";
		}else{
			upLevel = treeNode.path;
		}
		backupVar.backupLog.dsId = treeNode.dsId;
		backupVar.pages.pageSize = 5
		jbackupMore.css("display","block");
    	var p = treeNode.getParentNode();
    	zPath = treeNode.name;
    	while (p != null){
    		zPath = p.name + " / " + zPath;
	    	p = p.getParentNode();
    	}
    	jaddress.html(zPath);
		getList();
		getBackuplogs();
   }
	
	$W = $(window).width();
	$H = $(window).height();
	w = $(".window").width(); 
	h = $(".window").height();
	$(".window").css("top",(($H-h)/2)-80);
	$(".window").css("left",($W-w)/2);
	setInterval("getDownloadProcessBar()", 2500);
	
})
    
    function getFont(treeId, node) {
        return node.font ? node.font : {};
    }
    
    function getTree(json,nodes){
    	for(var i = 0;i<json.length; i++){
			var data = {};
			data.id = json[i].id;
			data.name = json[i].name;
			data.pId = json[i].pid;
			data.type = (parseInt(json[i].type) + 1)+"";
			data.version = json[i].version;
			data.path = json[i].path;
			data.root = json[i].root;
			data.dsId = json[i].dsId;
			data.isParent = true;
			if(json[i].type == "0"){
				data.iconSkin = "sty01"
			}else if(json[i].type == "1"){
				data.iconSkin = "sty02"
			}else{
				data.iconSkin = "sty03"
			}
			nodes[i] = data;
		}
    }
    
    function fileSizeTransfer(size){
		var fileSize = size;
		if(size/1024 > 1){
			fileSize = size/1024.0;
			fileSize = fileSize.toFixed(2);
			fileSize += "KB";
		}else{
			fileSize += "B";
		}
		if(size/(1024*1024) > 1){
			fileSize =size/(1024.0*1024);
			fileSize = fileSize.toFixed(2);
			fileSize += "MB";
		}
		if(size/(1024*1024*1024) > 1){
			fileSize = size/(1024.0*1024*1024);
			fileSize = fileSize.toFixed(2);
			fileSize += "GB";
		}
		return fileSize;
	}

    //2015年11月13日09:07:01
    function directors(dsId,path,version,name,bartd_id,nid){
    	
    	if(service.nids && service.nids[nid]){
    		plugin.msgtip({type:"e",msg:"正在恢复。。。"});
    		return;
    	}
    	
    	
    	$("#h_dsId").val(dsId);
    	$("#h_path").val(path);
    	$("#h_bartd_id").val(bartd_id);
    	if(nid){
    		$("#h_nid").val(nid);
    	}
    	service.getBackuplogs(getBackupWrapper(dsId), backupLogCB);
    	
    }
    function files(dsId,path,version,name,bartd_id,nid){
    	$("#h_dsId").val(dsId);
    	$("#h_bartd_id").val(bartd_id);
    	$("#h_path").val(path+"\\"+name);
    	if(nid){
    		$("#h_nid").val(nid);
    	}
    	var service1 = new EbeimService();
    	service1.getFileChangeLog({
    		dsId:dsId,
    		path:encodeURIComponent(path),
    		version:version,
    		name:encodeURIComponent(name)
    	}, fileChangeLogBC);
    }
    
    var fileChangeLogBC = function (data) {
        var json = eval("(" + data + ")");
    	var list = json.list.objList;
    	
    	var content = "";
    	for (var i = 0; i < (list.length>5?5:list.length); i++) {
    		var obj = list[i];
    		content = content
    		+"<li>"
    		+"<span style='float:left;'><button onclick='selectRecoveryPath(\"\"),setHideVersion(\""+obj.version+"\")' class='btn'>恢复至</button></span>"
    		+"<span style='float:right;'>"+getTimeStr(obj.logTime)+"</span>"
    		+"</li>";
    	}
    	$(".filechangelog-ul").html(content);
    	showDialog("versionWindow");
    	
    };

    function getBackupWrapper(dsId) {
    	var backupLog = {
    		dsId : dsId,
    		status:0
    	}
    	var pages = {
    		startPos : 0,
    		pageSize : 5
    	}
    	var json = {};
    	json["backupLog"] = backupLog;
    	json["pages"] = pages;

    	return json;
    }

    var backupLogCB = function(data){
    	var list = data.list.objList;
    	var size = list.length;
    	var content = "";
    	for (var i = 0; i < size; i++) {
    		obj = list[i];
    		content = content
    		+"<li>" 
    		+"<span style='float:left;'><button onclick='selectRecoveryPath(\"\"),setHideVersion(\""+obj.versionMajor+".0\")' class='btn'>恢复至</button></span>"
    		+"<span style='float:right;'>"+getTimeStr(obj.beginTime)+"</span>"
    		+"</li>";
    	}
    	if(size==0){
    		content = content
    		+"<li style='text-align:center'>暂无可恢复的版本!</li>";
    	}
    	$(".filechangelog-ul").html(content);
    	showDialog("versionWindow");
    };
    function setHideVersion(version){
    	$("#h_version").val(version);
    }
    function selectRecoveryPath(path){
    	$(".window").css("display","block");
    	$(".shadowDiv").css("display","block");
    	var abDir = $("#ab-dir").html();
    	if(abDir!=""){
    		$("#ab-dir").html(abDir+"\\"+path);
    		service.getSystemDirs({
    			path:abDir+"\\"+path,
    			action:"recovery"
    		}, selectRecoveryPathCB);
    	}else{
    		$("#ab-dir").html(path);
    		service.getSystemDirs({
    			path:path,
    			action:"recovery"
    		}, selectRecoveryPathCB);
    	}
    }
    var selectRecoveryPathCB = function(data){
    	var json = data;
    	var content = "";
    	for (var i = 0; i < json.length; i++) {
    		var name = json[i].name;
    		
    		var showName = name;
    		if(showName.indexOf("\Desktop")!=-1){
    			showName = "桌面"
    		    name = name.split("\\").join("\\\\");
    		}
    		content = content +
    		"<li><a href='javascript:selectRecoveryPath(\""+name+"/\")'>"+showName+"</a></li>";
    	}
    	$(".w-dir-list ul").html(content);
    }
    function selectParentPath(path){
    	var abDir = $("#ab-dir").html();
    	var idx = abDir.lastIndexOf("\\");
    	if(idx!=-1){
    		abDir = abDir.substring(0,idx);
    		$("#ab-dir").html(abDir);
        	service.getSystemDirs({
        		path:abDir
        	}, selectRecoveryPathCB);
    	}else{
    		$("#ab-dir").html("");
    		service.getSystemDirs({
    			path:""
    		}, selectRecoveryPathCB);
    	}
    }

    function confirmDir(){
    	var version = $("#h_version").val();
    	recovery(version);
    }
    function cancelDir(){
    	clearDateAndWindow();
    }

    function recovery(version,dynamicCode){
    	var dsId = $("#h_dsId").val();
    	var path ="/"+$("#h_path").val();
    	var abDir = $("#ab-dir").html();
    	var nid = $("#h_nid").val();
    	
    	setNId(nid, true);
    	
    	if(abDir == ""){
    		plugin.msgtip({type:"e",msg:"请选择下载目录"});
    		return;
    	}
    	$("#recoveyBtn").attr("disabled","disabled");
    	service.recoveryFile({
    		dsId:dsId,
    		path:encodeURIComponent(path),
    		version:version,
    		dynamicCode:dynamicCode,
    		abDir:encodeURIComponent(abDir),
    		nid:nid
    	},  function(data){
    		if(data.code=="200" || data.code==200){
    			
    		}else{
    			setNId(nid,false);
    		}
    		recoveryCB(data);
    	});
    }

    var recoveryCB = function(data){
    	$("#recoveyBtn").removeAttr("disabled");
    	var json = data;
    	if(json.code=="200" || json.code==200){
    		
    		clearDateAndWindow();
    		
    		var td_id = $("#h_bartd_id").val();
        	$("#"+td_id).parent().find("td").find(".tipspan").html("等待链接...");
       		var content = ""
       		+"<div style='width:120px;height:20px;border:solid 1px #B8C86C;margin:0 auto;position:relative;'>"
       		+"<div id='processbar' style='width:0px;height:20px;background:#B8C86C;'></div>"
       		+"<div class='r-info' style='line-height:20px;text-align:center;position:absolute;top:0;left:0;width:100%;height:20px;'>下载进度:<span id='percentage' style='color:green'>0.00%</span></div>"
       		+"</div>";
       		
       		var td_id = $("#h_bartd_id").val();
       		$("#"+td_id).html(content);
       		
    	 }else{
    		 dsSecurityRankCheck(json,json.message);
    	 }
    }

    function clearDateAndWindow(){
    	$("#dynamicCode").val("");
    	$("#ab-dir").html("");
    	hideDialog("versionWindow");
    	closeCodeWindow();
    	$(".window").css("display","none");
    	$(".shadowDiv").css("display","none");
    }

    function setDynamicCode(){
    	var dynamicCode = $("#dynamicCode").val();
    	if(dynamicCode == ""){
    		 plugin.msgtip({type: "e", msg: "动态验证码不能为空!"});
    		return;
    	}
    	var h_whichGetModel = $("#h_whichGetModel").val();
    	if(h_whichGetModel=="handBackup"){
    		var dsSecurityRank = $("#h_dsSecurityRank").val();
    		handBackup($dsId, dsSecurityRank, dynamicCode);
    	}else{
    		var version = $("#h_version").val();
    		recovery(version,dynamicCode);
    	}
    	
    }

    function getDownloadProcessBar() {

    	var ids = "";
    	$(".bartd").each(function() {
    		ids += $(this).attr("nid") + ",";
    	});
    	if (ids.length > 0) {
    		ids = ids.substring(0, ids.length - 1);
    		service.getDownloadProcessBar({
    			nids:ids
    		}, processbarCB);
    		service.deleteDownloadProcessBar({
    			nids:ids
    		}, delProcessbarCB);
    	}
    }


    var processbarCB = function(data){
    	var json = data;
    	var list = json.beans;
    	if(list.length<=0){
    		$(this).parent().find("td").find(".tipspan").html("");
			$(this).html("下载完成!");
			return ;
    	}
    	for (var i = 0; i < list.length; i++) {
    		var bean = list[i];
    		$(".bartd").each(function(){
    			var nid = $(this).attr("nid");
    			if (nid == bean.nid) {
    				setNId(nid, true);
    				var count = bean.count;
    				var total = bean.total;
    				var fileSum = bean.fileSum;
    				var okSum = bean.okSum;
    				var errorSum = bean.errorSum;
    				var percent = (count/total)*100;
    				
    				var isWhole = $(this).attr("class");
    				if(isWhole.indexOf("whole")!=-1){
    					$(this).css("display","block");
    				}
    				
    				var content = ""
    			   		+"<div style='width:100px;height:20px;border:solid 1px #B8C86C;margin:0 auto;position:relative;'>"
    			   		+"<div id='processbar' style='width:0px;height:20px;background:#B8C86C;'></div>"
    			   		+"<div class='r-info' style='line-height:20px;text-align:center;position:absolute;top:0;left:0;width:100%;height:20px;'>下载进度:<span id='percentage' style='color:green'>0.00%</span></div>"
    			   		+"</div>";
    				$(this).html(content);
    				
    				if(count >= total || okSum+errorSum>=fileSum){
    					$(this).parent().find("td").find(".tipspan").html("");
    					$(this).html("下载完成!");
    					setNId(nid, false);
    					if(bean.nid.indexOf('DS-')!=0){ 
    						setTimeout(function(){
    							$("#j-reset").click();
    						}, 3000);
    					}
    					if(total==0){
    						service.deleteDownloadProcessBarByNid({nid:nid}, function(data){;})
    					}
    				}else if(count == -1 || errorSum==fileSum){
    					setNId(nid, false);
    					$(this).find(".r-info").html("<font color='red'>下载失败！</font>");
    					service.deleteDownloadProcessBarByNid({
    						nid:nid
    					}, function(data){;});
    				}else{
    	    			$(this).parent().find("td").find(".tipspan").html("正在下载...");
    	    			$(this).find("#processbar").css("width",percent+"%");
    	    			$(this).find("#percentage").html((Math.floor(percent*100)/100)+"%");
    				}
    			}
    		});
    	}
    }
    var delProcessbarCB = function(data) {
    	var json = data;
    }
